package com.huawang.mdesign.model.service.util;

import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @author cdl
 */
public class StringContext {

    private StringContext() {
    }

    private static final ThreadLocal<Map<String, String>> CONTAINER = new InheritableThreadLocal<>();

    public static void set(String key, String value) {
        Optional.ofNullable(key).filter(StringUtils::isNotBlank).ifPresent(e -> getContainer().put(e, value));
    }

    @Nullable
    public static String get(String key) {
        return getContainer().get(key);
    }

    private static @NotNull Map<String, String> getContainer() {
        Map<String, String> map = CONTAINER.get();
        if (Objects.isNull(map)) {
            map = new HashMap<>();
            CONTAINER.set(map);
        }
        return map;
    }

    public static void remove() {
        CONTAINER.remove();
    }
}
